class EventsController < ApplicationController
  
  before_filter :login_required, :only => [:new, :create, :destroy, :invite, :remove_duplicated_invitation]
  
  def new
    @event = Event.new
    @pagetitle = "crear nuevo evento"
  end
  
  def create
    @event = Event.new(params[:event])
    @pagetitle = "crear nuevo evento"
    
    # Time.local(2000,"jan",1,20,15,1)
    starts_at_parse = correct_date(params[:event_time][:starts_at])
    @event.starts_at = Time.parse("#{starts_at_parse}, #{params[:event_time]['starts_at(4i)']}:#{params[:event_time]['starts_at(5i)']}")
    unless params[:has_ends_date].blank?
      ends_at_parse = correct_date(params[:event_time][:ends_at])
      @event.ends_at = Time.parse("#{ends_at_parse}, #{params[:event_time]['ends_at(4i)']}:#{params[:event_time]['ends_at(5i)']}")
    end
    @event.tag_list = params[:tag_list]
    @event.save
    redirect_to :controller => 'events', :action => 'invite', :id => @event.id
  end
  
  def show
    @event = Event.find(params[:id])
    if @event.private?
      render :template => 'events/private' and return if !logged_in? || !current_user.has_event?(@event)
    end
    @pagetitle = "#{@event.get_title}"
    
  end
  
  def update
    @event = Event.find(params[:id])
    @pagetitle = "actualizar #{@event.get_title}"
    
    return unless request.post?
    @event.update_attributes(params[:event])
    
    starts_at_parse = correct_date(params[:event_time][:starts_at])
    @event.starts_at = Time.parse("#{starts_at_parse}, #{params[:event_time]['starts_at(4i)']}:#{params[:event_time]['starts_at(5i)']}")
    unless params[:has_ends_date].blank?
      ends_at_parse = correct_date(params[:event_time][:ends_at])
      @event.ends_at = Time.parse("#{ends_at_parse}, #{params[:event_time]['ends_at(4i)']}:#{params[:event_time]['ends_at(5i)']}")
    end
    @event.tag_list = params[:tag_list]
    @event.save
    
  end
  
  
  def destroy
    
  end
  
  # invitar a un evento
  def invite
    @event = Event.find(params[:id])
    @pagetitle = "invita a quien tú quieras - #{@event.get_title}"
    redirect_to user_home_url and return if @event.user_id != current_user.id
    return unless request.post?
      params[:contact].each do |contact|
        unless contact['name'].blank? && contact['contact'].blank?
          contact = Contact.create(contact.merge(:event_id => params[:id]))
          invitation_code = Digest::SHA1.hexdigest("#{Time.now}_#{contact['contact']}").slice(4..9)
          invitation = Invitation.create({:code => invitation_code, :event_id => @event.id, :contact_id => contact.id})
          Notifier.deliver_event_invitation(contact['contact'], @event, invitation)
        end
      end
      
    respond_to do |format|
      format.html { redirect_to event_url(@event) }
      format.js
    end
  end
  
  def add_invitation
    respond_to do |format|
      format.js
    end
  end
  
  def copiagenda
    @event = Event.find(params[:id])
    @pagetitle = "invita desde tu agenda de móvil - #{@event.get_title}"
    
    redirect_to user_home_url and return if @event.user_id != current_user.id
    return unless request.post?
    begin
      @contacts = get_contacts(params[:login], params[:password])
    rescue
      flash[:alert] = "Parece que no encontramos tu agenda, vuelve a probar :)"
    end
  end
  
  def gmail
    @event = Event.find(params[:id])
    @pagetitle = "invita a tus contactos de gmail - #{@event.get_title}"
    
    redirect_to user_home_url and return if @event.user_id != current_user.id
    return unless request.post?
    
    begin
      GMailer.connect(params[:login], params[:password]) do |g|
        @contacts = g.fetch(:contact=>"all")
      end
    rescue
      flash[:alert] = "Parece que no hay manera de ver tus contactos, vuelve a probar :)"
    end
  end
  
  def tvienes_contacts
    @event = Event.find(params[:id])
    @pagetitle = "invita a tus contactos de tvienes - #{@event.get_title}"
    
    redirect_to user_home_url and return if @event.user_id != current_user.id
  end
  
  
  def add_user_to_event
    @event = Event.find(params[:id])
    redirect_to login_url and return unless logged_in?
    contact = Contact.create(:event_id => params[:id], :user_id => current_user.id, :confirm => true)
    redirect_to event_url(@event)
  end
  
  
  def accept_invitation
    @pagetitle = "gestion de invitaciones"
    
    begin
      # revisar este comportamiento
      @invitation = Invitation.find_by_code(params[:code])
      redirect_to home_url and return if @invitation.blank?
      @event = @invitation.event
      # comprobación de que no tengamos más de una invi aceptada por usuario
      if logged_in?
        unless @event.contacts.find_by_user_id(current_user.id, :conditions => "confirm >= 0").blank?
          render :template => 'events/duplicated_invitation' and return
        end
      end
      
      session["invitation"] = params[:code]
      if logged_in?
        if @invitation.contact.user.nil? || @invitation.contact.user == current_user
          # si la invitación es nueva le asignamos el usuario que la ha pedido
          @invitation.contact.update_attribute('user_id', current_user.id) if @invitation.contact.user_id.nil?
          unless params[:accept].nil?
            @invitation.contact.update_attribute('confirm', params[:accept])
            @invitation.destroy
            session["invitation"] = nil
            redirect_to event_url(@event)
          end
        else
          # estás intentando ver una invitación que no es tuya
          redirect_to home_url
        end
      end
    rescue
      session["invitation"] = nil
      redirect_to home_url
    end
  end
  
  def forget_invitation
    session["invitation"] = nil
    respond_to do |format|
      format.html { redirect_to home_url }
      format.js
    end
  end
  
  def remove_duplicated_invitation
    session["invitation"] = nil
    @invitation = Invitation.find_by_code(params[:code])
    @event = @invitation.event
    @invitation.contact.destroy
  end
  
  
  def comments
    @event = Event.find(params[:id])
  end

  # enviar información del evento vía sms
  def sms_event
    @event = Event.find(params[:id])
    Notifier.deliver_event_info(current_user, @event)
    respond_to do |format|
      format.html {
        redirect_to event_url(@event)
      }
      format.js
    end
  end
  
  def correct_date(datestring)
    datestring.gsub!("Enero", "Jan")
    datestring.gsub!("Febrero", "Feb")
    datestring.gsub!("Marzo", "Mar")
    datestring.gsub!("Abril", "Apr")
    datestring.gsub!("Mayo", "May")
    datestring.gsub!("Junio", "Jun")
    datestring.gsub!("Julio", "Jul")
    datestring.gsub!("Agosto", "Aug")
    datestring.gsub!("Septiempre", "Sep")
    datestring.gsub!("Octubre", "Oct")
    datestring.gsub!("Noviembre", "Nov")
    datestring.gsub!("Diciembre", "Dec")
    datestring
  end
  
  
end
